package cn.edu.ahu.aircondition.modbus.service;

import cn.edu.ahu.aircondition.modbus.service.domain.CtrlDomain;
import cn.edu.ahu.aircondition.modbus.service.domain.*;
import cn.edu.ahu.aircondition.modbus.service.domain.Response;
import cn.edu.ahu.aircondition.modbus.service.entity.*;
import cn.edu.ahu.aircondition.modbus.service.service.*;
import cn.edu.ahu.aircondition.modbus.service.serviceImpl.*;

import javax.xml.bind.Element;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * Created by ahu on 2017/6/11.
 */
public class TimerApi {
    private AirConService airConService = new AirConServiceImpl();
    private ModReadAndWriteSer modReadAndWriteSer = new ModReadAndWriteSerImpl();

    public QueryRegDomain querySingle(Integer deviceAddress) throws Exception{
        Response response = modReadAndWriteSer.getQueryFromReg(deviceAddress);
        AirConStatusEntity airConStatusEntity = new AirConStatusEntity();
        if (response.getMeta().isSuccess()){
            QueryRegDomain queryRegDomain = (QueryRegDomain)response.getData();
            airConStatusEntity.setDeviceAddress(deviceAddress);
            airConStatusEntity.setaTemp(queryRegDomain.getAirConCtrlTemp());
            airConStatusEntity.setAoc(queryRegDomain.getAoc());
            airConStatusEntity.setDwind(queryRegDomain.getWind());
            airConStatusEntity.setfModel(queryRegDomain.getModel());
            airConStatusEntity.setErrMsg(queryRegDomain.getErrMsg());
            airConStatusEntity.seteTemp(queryRegDomain.getEnvTemp());
            return queryRegDomain;
        }
        else
            return null;
    }

    /**
     * 根据set表中的Address信息，下发查询指令，跟新状态表，并增加状态流水表
     */
    public void queryData2DB(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //获取所有Address信息
        List<Integer> addressList = new ArrayList<Integer>();
        List<AirConStatuWaterEntity> waterEntityList = new ArrayList<AirConStatuWaterEntity>();
        List<AirConStatusEntity> newStatusEntityList = new ArrayList<AirConStatusEntity>();

        for (AirConSetEntity setEntity : airConService.listAirConSet()){
            addressList.add(setEntity.getDeviceAddress());
        }
        for (AirConStatusEntity oldData : airConService.listAirConStatusDeviceAddress(addressList)){
            try {
                Thread.sleep(100);
                QueryRegDomain newData = (QueryRegDomain) modReadAndWriteSer.
                        getQueryFromReg(oldData.getDeviceAddress()).getData();
                AirConStatusEntity newEntity  = new AirConStatusEntity();

                newEntity.setAoc(newData.getAoc());
                newEntity.setDeviceAddress(newData.getDeviceAddress());
                newEntity.setaTemp(newData.getAirConCtrlTemp());
                newEntity.setDwind(newData.getWind());
                newEntity.setfModel(newData.getModel());
                newEntity.setErrMsg(newData.getErrMsg());
                newEntity.seteTemp(newData.getEnvTemp());
                newEntity.setUpdateTime(String.valueOf(df.format(new Date())));

                AirConStatusEntity waterEntity  = airConService.queryDataCompare(oldData,newData);
                if (waterEntity != null){//空调状态发生改变，要写流水表
                    waterEntityList.add(new AirConStatuWaterEntity(waterEntity));
                    newEntity.setAocTime(waterEntity.getAocTime());
                    newEntity.setUpdateTime(String.valueOf(df.format(new Date())));
                }
                else {
                    newEntity.setAocTime(oldData.getAocTime());
                }
                newStatusEntityList.add(newEntity);//待更新本地表
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //跟新状态表以及更新流水表
        airConService.updateAirConStatus(newStatusEntityList);
        airConService.saveAirStatusWater(waterEntityList);
    }

    /**
     * 从控制表中获取所有的控制信息
     * @return 控制结果
     * @throws Exception
     */
    public void setDevice(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        List<CtrlRegDomain> ctrlRegEntityList =
                airConService.listCtrlRegDomain();
        List<CtrlDomain> ctrlDomainList = airConService.listCtrlDomain();
        HashMap<Integer,AirConCtrlEntity> ctrlEntityHashMap = new HashMap<Integer, AirConCtrlEntity>();
        //设立一张hashmap，用于将deviceId和AirConCtrlEntity对应
        for (CtrlDomain ctrlDomain :ctrlDomainList){
            ctrlEntityHashMap.put(ctrlDomain.getAirConSetEntity().getDeviceId(),
                    ctrlDomain.getAirConCtrlEntity());
        }

        for (CtrlRegDomain ctrlRegDomain:ctrlRegEntityList){
            Response response = modReadAndWriteSer.setCtrlToReg(ctrlRegDomain);
            AirConCtrlEntity newCtrlEntity = ctrlEntityHashMap.get(ctrlRegDomain.getDeviceId());
            newCtrlEntity.setUpdateTime(String.valueOf(df.format(new Date())));
            //如果发送失败
            if (!response.getMeta().isSuccess()){
                newCtrlEntity.setStatus("执行失败");
                ctrlEntityHashMap.put(ctrlRegDomain.getDeviceId(),newCtrlEntity);
            }
            else {//发送成功
                newCtrlEntity.setStatus("执行成功");
                ctrlEntityHashMap.put(ctrlRegDomain.getDeviceId(),newCtrlEntity);
            }
        }
        List<AirConCtrlEntity> newCtrlEntityList = new ArrayList<AirConCtrlEntity>();
        for (Integer mapKey:ctrlEntityHashMap.keySet()){
            newCtrlEntityList.add(ctrlEntityHashMap.get(mapKey));
        }

        //更新控制表
        airConService.updateAirConCtrl(newCtrlEntityList);
    }
}
